<template>
  <basic-dialog
    :visible="visible"
    :title="dialogTitle"
    align-center
    :loading="loading"
    width="max-content"
    @open="handleDialogOpen"
    @submit="handleSubmit"
    @closed="handleCloseDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-position="top"
      require-asterisk-position="right"
    >
      <el-form-item label="分组名称" prop="name" required>
        <el-input
          v-model="formData.name"
          placeholder="请输入分组名称"
          maxlength="30"
        ></el-input>
      </el-form-item>

      <el-form-item class="hidden" prop="user_ids" />

      <basic-transfer
        v-if="visible"
        v-model="formData.user_ids"
        class="mb-[18px]"
        :data="userList"
        :props="{
          key: 'id',
          label: 'name'
        }"
        :loading="transferLoading"
      ></basic-transfer>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          class="w-full"
          placeholder="请输入备注"
          maxlength="200"
          show-word-limit
        ></el-input>
      </el-form-item>
    </el-form>
  </basic-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

import type { CommonParams } from '@/apis/model/_utils'
import type { UserGroupModel, UserModel } from '@/apis/model/user'
import ToastUtils from '@/utils/toast'

interface IProps {
  visible: boolean
  record?: UserGroupModel | null
  loading?: boolean
}

const transferLoading = ref(false)

interface IEmit {
  (event: 'update:visible', val: boolean): void
  (event: 'update:loading', val: boolean): void
  (event: 'reload'): void
}

const emit = defineEmits<IEmit>()
const props = defineProps<IProps>()

const formRef = ref<FormInstance>()

// dialog 标题
const dialogTitle = computed(() => (props.record?.id ? '编辑分组' : '新建分组'))

type IFrom = CommonParams<'/v1/user_group', 'post'>
const formData = reactive<IFrom & { user_ids: string[] }>({
  name: '',
  user_ids: [],
  remark: ''
})

const rules: Record<string, FormItemRule[]> = {
  name: [{ required: true, message: '请输入分组名称', trigger: 'blur' }]
}

/**
 * 用户列表
 */
const userList = ref<
  {
    id: string
    name: string
  }[]
>([])

const getUserList = (username?: string) => {
  transferLoading.value = true
  userListApi({ username, offset: 0, limit: 0 })
    .then(res => {
      const list = res.list as UserModel[]
      formData.user_ids = list
        .filter(v => v.group_id === props.record?.id)
        .map(v => v.id!)

      userList.value = list
        .filter(v => v.group_id === '0' || v.group_id === props.record?.id)
        .map(item => ({
          id: item.id!,
          name: item.username!
        }))
    })
    .finally(() => {
      transferLoading.value = false
    })
}
watchEffect(() => {
  if (props.visible) {
    getUserList()
  }
})

/**
 * 保存操作
 */
const handleSubmit = async () => {
  await formRef.value?.validate()
  emit('update:loading', true)
  try {
    if (props.record?.id) {
      await putUserGroupApi({ id: props.record?.id as string, ...formData })
    } else {
      await postUserGroupApi(formData)
    }
    emit('reload')
    emit('update:visible', false)
    ToastUtils.success(props.record?.id ? '修改成功' : '创建成功')
  } finally {
    emit('update:loading', false)
  }
}

/**
 * dialog打开
 */
const handleDialogOpen = () => {
  formData.name = props.record?.name
  formData.remark = props.record?.remark
}

/**
 * 关闭dialog
 */
const handleCloseDialog = () => {
  emit('update:visible', false)
  emit('update:loading', false)
  userList.value = []
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss"></style>
